package main

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"gopkg.in/yaml.v2"
)

func main() {
	// 至少一个ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      "127.0.0.1",
			Port:        8848,
			Scheme:      "http",
			ContextPath: "/nacos",
		},
	}

	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "public", // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/xlog",
		CacheDir:            "/tmp/nacos/cache", // 不加/ 开头的路径默认在更目录下下
		LogLevel:            "debug",
		Username:            "nacos",
		Password:            "nacos",
	}
	// 创建动态配置客户端的另一种方式 (推荐)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(err)
	}
	// 获取配置信息
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: "mysql",
		Group:  "dev_food_platform",
	})
	if err != nil {
		fmt.Println("GetConfig err: ", err)
		return
	}
	var conf RpcConfig
	err = yaml.Unmarshal([]byte(content), &conf)
	if err != nil {
		fmt.Println("yaml err: ", err)
		return
	}
	fmt.Printf("conf: %+v", conf)
	return
}

type RpcConfig struct {
	Env      string         `yaml:"env"`
	Kitex    KitexLogConfig `yaml:"kitex"`
	Registry RegistryConfig `yaml:"registry"`
	MySQL    MySQLConfig    `yaml:"mysql"`
	Redis    RedisConfig    `yaml:"redis"`
}

type KitexLogConfig struct {
	Service       string `yaml:"service"`
	Address       string `yaml:"address"`
	LogLevel      string `yaml:"log_level"`
	LogFileName   string `yaml:"log_file_name"`
	LogMaxSize    int    `yaml:"log_max_size"`
	LogMaxAge     int    `yaml:"log_max_age"`
	LogMaxBackups int    `yaml:"log_max_backups"`
}

type RegistryConfig struct {
	RegistryAddress []string `yaml:"registry_address"`
	Username        string   `yaml:"username"`
	Password        string   `yaml:"password"`
}

type MySQLConfig struct {
	DSN string `yaml:"dsn"`
}

type RedisConfig struct {
	Address  string `yaml:"address"`
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	DB       int    `yaml:"db"`
}
